package com.jyx.manage_course.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jyx.framework.domain.cms.CmsPage;
import com.jyx.framework.domain.cms.response.CmsPageResult;
import com.jyx.framework.domain.cms.response.CmsPostPageResult;
import com.jyx.framework.domain.course.*;
import com.jyx.framework.domain.course.ext.CourseInfo;
import com.jyx.framework.domain.course.ext.CourseView;
import com.jyx.framework.domain.course.ext.TeachplanNode;
import com.jyx.framework.domain.course.request.CourseListRequest;
import com.jyx.framework.domain.course.response.CourseCode;
import com.jyx.framework.domain.course.response.CoursePublishResult;
import com.jyx.framework.exception.ExceptionCast;
import com.jyx.framework.model.response.CommonCode;
import com.jyx.framework.model.response.QueryResponseResult;
import com.jyx.framework.model.response.QueryResult;
import com.jyx.framework.model.response.ResponseResult;
import com.jyx.framework.utils.DateFormat;
import com.jyx.manage_course.client.CmsPageClient;
import com.jyx.manage_course.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class CourseService {
    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    CourseBaseRepository courseBaseRepository;
    @Autowired
    CoursePubRepository coursePubRepository;
    @Autowired
    TeachplanRepository teachplanRepository;
    @Autowired
    CoursePicRepository coursePicRepository;
    @Autowired
    CourseMarketRepository courseMarketRepository;
    @Autowired
    CmsPageClient cmsPageClient;
    @Autowired
    TeachplanMediaRepository teachplanMediaRepository;
    @Autowired
    TeachplanMediaPubRepository teachplanMediaPubRepository;

    @Value("${course-publish.dataUrlPre}")
    private String publish_dataUrlPre;
    @Value("${course-publish.pagePhysicalPath}")
    private String publish_page_pagePhysicalPath;
    @Value("${course-publish.pageWebPath}")
    private String publish_page_webpath;
    @Value("${course-publish.siteId}")
    private String publish_page_siteId;
    @Value("${course-publish.templateId}")
    private String publish_page_templateId;
    @Value("${course-publish.previewUrl}")
    private String previewUrl;

    public TeachplanNode findTeachplanNodeById(String courseId){
        TeachplanNode teachplanNode = teachplanMapper.selectList(courseId);
        return teachplanNode;
    }

    /**
     * 获取根结点，如果没有则创建根结点
     */
    public String getTeachplanRoot(String courseId){
        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(courseId);
        if(!courseBaseOptional.isPresent()){
            return null;
        }
        CourseBase courseBase = courseBaseOptional.get();

        //取出
        List<Teachplan> teachplans = teachplanRepository.findByCourseidAndParentid(courseId, "0");
        if(teachplans == null || teachplans.size() == 0){
            //新增一个结点
            Teachplan teachplanRoot = new Teachplan();
            teachplanRoot.setCourseid(courseId);
            teachplanRoot.setPname(courseBase.getName());
            teachplanRoot.setParentid("0");
            teachplanRoot.setGrade("1");
            teachplanRoot.setStatus("0");
            teachplanRepository.save(teachplanRoot);
            return teachplanRoot.getId();
        }
        Teachplan teachplan = teachplans.get(0);
        return teachplan.getId();
    }

    /**
     * 添加课程计划，要先判断有没有父节点。
     * @param teachplan
     * @return
     */
    @Transactional
    public ResponseResult addTeachplan(Teachplan teachplan){
        //先判断课程信息
        if(teachplan == null || StringUtils.isEmpty(teachplan.getCourseid())||StringUtils.isEmpty(teachplan.getPname())){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        //在取出父节点并判断
        String courseId = teachplan.getCourseid();
        String parentId = teachplan.getParentid();
        if(StringUtils.isEmpty(parentId)){
            parentId = getTeachplanRoot(courseId);
        }
        //取出父节点信息
        Optional<Teachplan> teachplanParentOptional = teachplanRepository.findById(parentId);
        if(!teachplanParentOptional.isPresent()){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        Teachplan teachplanParent = teachplanParentOptional.get();
        String parentGrade = teachplanParent.getGrade();
        teachplan.setParentid(parentId);
        teachplan.setStatus("0");
        //通过父节点级别判断子结点，最多3级
        if(parentGrade.equals("1")){
            teachplan.setGrade("2");
        }else if(parentGrade.equals("2")){
            teachplan.setGrade("3");
        }
        //设置课程id
        teachplan.setCourseid(teachplanParent.getCourseid());
        teachplanRepository.save(teachplan);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 分页查找课程列表
     * @param page
     * @param size
     * @param courseListRequest
     * @return
     */
    public QueryResponseResult findCourseList(String companyId,int page, int size, CourseListRequest courseListRequest) {
        if(page == 0){
            page = 1;
        }
        if(size == 0){
            size = 10;
        }
        if(courseListRequest == null){
            courseListRequest = new CourseListRequest();
        }
        courseListRequest.setCompanyId(companyId);
        PageHelper.startPage(page, size);
        Page<CourseInfo> courseListPage = courseMapper.findCourseListPage(courseListRequest);
        if(courseListPage.isEmpty()){
            return new QueryResponseResult(CommonCode.SUCCESS, null);
        }
        List<CourseInfo> courseListPageResult = courseListPage.getResult();
        QueryResult<CourseInfo> queryResult = new QueryResult<>();
        queryResult.setList(courseListPageResult);
        List<CourseBase> baseRepositoryAll = courseBaseRepository.findAll();
        queryResult.setTotal(baseRepositoryAll.size());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }



    /**
     * 添加课程
     * @param courseBase
     * @return
     */
    public ResponseResult addCourse(CourseBase courseBase) {
        if(courseBase == null){
            ExceptionCast.cast(CourseCode.COURSE_COURSEISNULL);
        }

        courseBaseRepository.save(courseBase);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 查询课程基本信息
     * @param id
     * @return
     */
    public CourseBase queryCourseBaseById(String id) {
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(id);
        if(optionalCourseBase.isPresent()){
            CourseBase courseBase = optionalCourseBase.get();
            return courseBase;
        }
        return null;
    }
    public CourseBase getCourseBaseById(String id){
        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(id);
        if(courseBaseOptional.isPresent()){
            return courseBaseOptional.get();
        }
        return null;
    }

    /**
     * 修改课程基本信息
     * @param courseBase
     * @return
     */
    public ResponseResult editCourse(String id,CourseBase courseBase) {
        CourseBase courseBaseById = this.getCourseBaseById(id);
        if(courseBaseById != null){
            /**
             *  private String name;
             *     private String users;
             *     private String mt;
             *     private String st;
             *     private String grade;
             *     private String studymodel;
             *     private String description;
             */
            courseBaseById.setName(courseBase.getName());
            courseBaseById.setUsers(courseBase.getUsers());
            courseBaseById.setMt(courseBase.getMt());
            courseBaseById.setSt(courseBase.getSt());
            courseBaseById.setGrade(courseBase.getGrade());
            courseBaseById.setStudymodel(courseBase.getStudymodel());
            courseBaseById.setDescription(courseBase.getDescription());
            CourseBase save = courseBaseRepository.save(courseBaseById);
            if(save!=null){
                return new ResponseResult(CommonCode.SUCCESS);
            }
        }
        CourseBase save = courseBaseRepository.save(courseBase);
        if(save!=null){
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CourseCode.COURSE_COURSEISNULL);
    }

    /**
     * 添加图片信息
     * @param courseId
     * @param pic
     * @return
     */
    public ResponseResult addCoursePicById(String courseId, String pic) {
        //查重
        Optional<CoursePic> coursePicOptional = coursePicRepository.findById(courseId);
        CoursePic coursePic = null;
        if(coursePicOptional.isPresent()){
            coursePic = coursePicOptional.get();
        }
        if(coursePic == null){
            coursePic = new CoursePic();
        }
        coursePic.setCourseid(courseId);
        coursePic.setPic(pic);
        coursePicRepository.save(coursePic);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 删除文件
     * @param courseId
     * @return
     */
    public ResponseResult delCoursePicById(String courseId) {
        Optional<CoursePic> coursePicOptional = coursePicRepository.findById(courseId);
        if(!coursePicOptional.isPresent()){
            ExceptionCast.cast(CourseCode.COURSE_COURSEPICISNULL);
        }
        coursePicRepository.deleteById(courseId);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 查找课程图片信息
     * @param courseId
     * @return
     */
    public CoursePic findCoursePic(String courseId) {
        Optional<CoursePic> coursePicOptional = coursePicRepository.findById(courseId);
        if(coursePicOptional.isPresent()){
            return coursePicOptional.get();
        }
        return null;
    }

    //课程视图查询
    public CourseView getCourseView(String id) {
        CourseView courseView = new CourseView();
        //查课程基本信息
        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(id);
        if(courseBaseOptional.isPresent()){
            CourseBase courseBase = courseBaseOptional.get();
            courseView.setCourseBase(courseBase);
        }
        //查课程图片信息
        Optional<CoursePic> coursePicOptional = coursePicRepository.findById(id);
        if(coursePicOptional.isPresent()){
            CoursePic coursePic = coursePicOptional.get();
            courseView.setCoursePic(coursePic);
        }
        //查课程优惠信息
        Optional<CourseMarket> courseMarketOptional = courseMarketRepository.findById(id);
        if(courseMarketOptional.isPresent()) {
            CourseMarket courseMarket = courseMarketOptional.get();
            courseView.setCourseMarket(courseMarket);
        }
        //查课程计划信息
        TeachplanNode teachplanNode = teachplanMapper.selectList(id);
        courseView.setTeachplanNode(teachplanNode);
        return courseView;
    }
    //课程预览
    public CoursePublishResult preview(String id) {
        //先查课程基本信息
        CourseBase courseBaseById = this.findCourseBaseById(id);
        CmsPage cmsPage = new CmsPage();
        cmsPage.setSiteId(publish_page_siteId);
        cmsPage.setTemplateId(publish_page_templateId);
        cmsPage.setPageName(courseBaseById.getId()+".html");
        cmsPage.setPageAliase(courseBaseById.getName());
        cmsPage.setPageWebPath(publish_page_webpath);
        cmsPage.setPagePhysicalPath(publish_page_pagePhysicalPath);
        cmsPage.setDataUrl(publish_dataUrlPre+id);
        //远程请求Cms保存页面
        CmsPageResult cmsPageResult = cmsPageClient.save(cmsPage);
        if(!cmsPageResult.isSuccess()){
            return new CoursePublishResult(CommonCode.FAIL, null);
        }
        //页面url
        String pageId = cmsPageResult.getCmsPage().getPageId();
        String pageUrl = previewUrl+pageId;
        return new CoursePublishResult(CommonCode.SUCCESS, pageUrl);
    }
    //根据id查询课程基本信息
    public CourseBase findCourseBaseById(String id){
        Optional<CourseBase> baseOptional = courseBaseRepository.findById(id);
        if(baseOptional.isPresent()){
            CourseBase courseBase = baseOptional.get();
            return courseBase;
        }
        return null;
    }
    //根据id查询课程基本信息
    public CourseMarket findCourseMarketById(String id){
        Optional<CourseMarket> courseMarketById = courseMarketRepository.findById(id);
        if(courseMarketById.isPresent()){
            CourseMarket CourseMarket = courseMarketById.get();
            return CourseMarket;
        }
        return null;
    }

    /**
     * 课程发布
     * @param courseId
     * @return
     */
    @Transactional
    public CoursePublishResult publish(String courseId) {
        //找到课程基本信息
        CourseBase courseBaseById = this.findCourseBaseById(courseId);
        //发布课程详情页面
        CmsPostPageResult cmsPostPageResult = publish_page(courseId);
        if(!cmsPostPageResult.isSuccess()){
            System.out.println("出错了！信息为："+cmsPostPageResult.getMessage());
            ExceptionCast.cast(CommonCode.FAIL);
        }
        //更新课程状态
        CourseBase courseBase = saveCoursePubState(courseId);
        //未来--课程索引、课程缓存
        saveTeachplanMediaPub(courseId);
        //获取页面url
        String pageUrl = cmsPostPageResult.getPageUrl();
        return new CoursePublishResult(CommonCode.SUCCESS,pageUrl);
    }

    /**
     * 保存课程发布表
     * @param
     * @return
     */
    private CourseBase saveCoursePubState(String courseId) {
        Optional<CourseBase> courseBaseById = courseBaseRepository.findById(courseId);
        CourseBase courseBase = courseBaseById.get();
        courseBase.setStatus("202002");
        CourseBase saveCourseBase = courseBaseRepository.save(courseBase);

        Optional<CoursePic> coursePicById = coursePicRepository.findById(courseId);
        CoursePic coursePic = null;
        if(coursePicById.isPresent()){
            coursePic = coursePicById.get();
        }
        CourseMarket courseBaseMarket = findCourseMarketById(courseId);
        CoursePub coursePub = null;
        //保存发布课程信息
        Optional<CoursePub> coursePubRepositoryById = coursePubRepository.findById(courseId);
        if(coursePubRepositoryById.isPresent()){
            coursePub = coursePubRepositoryById.get();
        }else {
            coursePub = new CoursePub();
            coursePub.setId(courseId);
        }
        coursePub.setName(courseBase.getName());
        if(courseBaseMarket != null) {
            coursePub.setCharge(courseBaseMarket.getCharge());
            coursePub.setPrice(courseBaseMarket.getPrice());
            coursePub.setPrice_old(courseBaseMarket.getPrice_old());
            coursePub.setValid(courseBaseMarket.getValid());
            coursePub.setQq(courseBaseMarket.getQq());
        }else {
            coursePub.setCharge("203001");
            coursePub.setValid("204001");
        }
        coursePub.setMt(courseBase.getMt());
        coursePub.setSt(courseBase.getSt());
        coursePub.setStudymodel(courseBase.getStudymodel());
        coursePub.setGrade(courseBase.getGrade());
        //coursePub.setTeachmode(courseBase.getTeachmode());
        coursePub.setUsers(courseBase.getUsers());
        coursePub.setDescription(courseBase.getDescription());
        if(coursePic != null) {
            coursePub.setPic(coursePic.getPic());
        }
        coursePub.setTimestamp(DateFormat.dateToTimestamp(new Date()));
        coursePub.setPubTime(DateFormat.dateToString(new Date()));
        TeachplanNode teachplanNode = findTeachplanNodeById(courseId);
        if(teachplanNode == null || teachplanNode.getChildren().isEmpty()){
            coursePub.setTeachplan(" ");
        }else {
            coursePub.setTeachplan(JSON.toJSONString(teachplanNode));
        }
        coursePubRepository.save(coursePub);
        /**
         private String teachplan;//课程计划
         private String pubTime;//课程发布时间
         */
        return saveCourseBase;
    }

    public CmsPostPageResult publish_page(String courseId){
        CourseBase courseBaseById = this.findCourseBaseById(courseId);
        //补充课程预览信息:站点id  模板id  名称  别名  页面访问web路径  页面存储路径 数据url
        CmsPage cmsPage = new CmsPage();
        cmsPage.setSiteId(publish_page_siteId);
        cmsPage.setTemplateId(publish_page_templateId);
        cmsPage.setPageName(courseId+".html");
        cmsPage.setPageAliase(courseBaseById.getName());
        cmsPage.setPageWebPath(publish_page_webpath);
        cmsPage.setPagePhysicalPath(publish_page_pagePhysicalPath);
        cmsPage.setDataUrl(publish_dataUrlPre+courseId);
        //一键发布页面
        CmsPostPageResult cmsPostPageResult = cmsPageClient.postPageQuick(cmsPage);
        return cmsPostPageResult;
    }

    /**
     * 保存课程计划视频信息
     * @param teachplanMedia
     * @return
     */
    public ResponseResult savemedia(TeachplanMedia teachplanMedia) {
        if(teachplanMedia == null){
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        String teachplanId = teachplanMedia.getTeachplanId();
        Optional<Teachplan> teachplanOptional = teachplanRepository.findById(teachplanId);
        if(!teachplanOptional.isPresent()){
            System.out.println("课程计划为空~！");
            ExceptionCast.cast(CourseCode.COURSE_MEDIA_TEACHPLAN_ISNULL);
        }
        Teachplan teachplan = teachplanOptional.get();
        String grade = teachplan.getGrade();
        if(StringUtils.isEmpty(grade) || !grade.equals("3")){
            System.out.println("课程分类不是为子节点~！");
            ExceptionCast.cast(CourseCode.COURSE_MEDIA_TEACHPLAN_GRADEERROR);
        }
        TeachplanMedia one = null;
        Optional<TeachplanMedia> teachplanMediaOptional = teachplanMediaRepository.findById(teachplanId);
        if(!teachplanMediaOptional.isPresent()){
            one = new TeachplanMedia();
        }else {
            one = teachplanMediaOptional.get();
        }
        one.setCourseId(teachplanMedia.getCourseId());
        one.setTeachplanId(teachplanId);
        one.setMediaFileOriginalName(teachplanMedia.getMediaFileOriginalName());
        one.setMediaId(teachplanMedia.getMediaId());
        one.setMediaUrl(teachplanMedia.getMediaUrl());
        teachplanMediaRepository.save(one);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * save teachplan media pub
     * @param courseId
     */
    private void saveTeachplanMediaPub(String courseId){
        System.out.println("==================开始查找媒体计划==================");
        List<TeachplanMedia> teachplanMediaList = teachplanMediaRepository.findByCourseId(courseId);
        System.out.println("==================开始删除发布的媒体计划==================");
        teachplanMediaPubRepository.deleteByCourseId(courseId);
        List<TeachplanMediaPub> teachplanMediaPubList = new ArrayList<>();
        for(TeachplanMedia teachplanMedia:teachplanMediaList){
            TeachplanMediaPub teachplanMediaPub = new TeachplanMediaPub();
            teachplanMediaPub.setCourseId(teachplanMedia.getCourseId());
            teachplanMediaPub.setMediaId(teachplanMedia.getMediaId());
            teachplanMediaPub.setMediaFileOriginalName(teachplanMedia.getMediaFileOriginalName());
            teachplanMediaPub.setMediaUrl(teachplanMedia.getMediaUrl());
            teachplanMediaPub.setTeachplanId(teachplanMedia.getTeachplanId());
            //BeanUtils.copyProperties(teachplanMedia,teachplanMediaPub);
            teachplanMediaPubList.add(teachplanMediaPub);
        }
        System.out.println("==================开始保存发布的媒体计划==================");
        teachplanMediaPubRepository.saveAll(teachplanMediaPubList);
    }

    public CoursePub getCoursePubById(String courseId) {
        Optional<CoursePub> coursePubOptional = coursePubRepository.findById(courseId);
        if(!coursePubOptional.isPresent()){
            System.out.println("课程发布信息为空~");
            return null;
        }
        return coursePubOptional.get();
    }
}
